package cn.yuanqiao.archive.appManager.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantFieldsMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantMdataListMapper;
import cn.yuanqiao.archive.appManager.service.ITenantMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import com.alibaba.fastjson2.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 元数据明细Service业务层处理
 *
 * @author yuanqiao
 * @date 2023-06-09
 */
@Service
public class TenantMdataListServiceImpl implements ITenantMdataListService
{
    @Autowired
    private TenantMdataListMapper yqdaMdataListMapper;
    @Autowired
    private TenantFieldsMapper tenantFieldsMapper;
    @Autowired
    private ITenantSysDictTypeService dictTypeService;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    /**
     * 查询元数据明细
     *
     * @param id 元数据明细主键
     * @return 元数据明细
     */
    @Override
    public TenantMdataList selectTenantMdataListById(Long id)
    {
        return yqdaMdataListMapper.selectTenantMdataListById(id,new TenantMdataList().getTableName());
    }

    @Override
    public Map<String, Object> selectTenantMdataListByIdAll(Long id) {
        Map<String, Object> map = new HashMap<>();
        map.put("HddaMDataList",yqdaMdataListMapper.selectTenantMdataListById(id,new TenantMdataList().getTableName()));
        return map;
    }

    /**
     * 查询元数据明细列表
     *
     * @param yqdaMdataList 元数据明细
     * @return 元数据明细
     */
    @Override
    public List<TenantMdataList> selectTenantMdataListList(TenantMdataList yqdaMdataList)
    {
        return yqdaMdataListMapper.selectTenantMdataListList(yqdaMdataList);
    }


    @Override
    public List<TenantMdataList> selectTenantMdataListListByCategoryId(TenantMdataList tenantMdataList, Long categoryId) {
        return yqdaMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList,categoryId,new TenantCategory().getTableName());
    }

    /**
     * 新增元数据明细
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTenantMdataList(String ids,Long groupId)
    {
        LoginUser user = SecurityUtils.getLoginUser();
        if(user == null){
            user = new LoginUser();
            user.setUserId(1L);
        }
        TenantFields fields = new TenantFields();
        fields.setIds(ids);
        List<TenantFields> yqFieldsList = tenantFieldsMapper.selectTenantFieldsList(fields);
        for(TenantFields data: yqFieldsList){
            //添加元数据明细
            TenantMdataList mDataList = new TenantMdataList();
            mDataList.setFieldCaption(data.getFieldCaption());
            mDataList.setGroupId(groupId);
            mDataList.setFieldName(data.getFieldName());
            mDataList.setFieldType(Integer.valueOf(data.getFieldType()));
            mDataList.setDataLength(Integer.valueOf(data.getFieldLength()));
            mDataList.setType(Integer.valueOf(data.getType()));
            mDataList.setShowType(Integer.valueOf(data.getShowType()));
            mDataList.setIsSystem(Integer.valueOf(data.getIsCommon()));

            mDataList.setDefaultValue(data.getDefaultVal());
            mDataList.setIsNoEmpty("true".equals(data.getNullable()) ? 0 : 1);

            //mDataList.setIsInput("true".equals(data.getNullAble()) ? 0 : 1);
            mDataList.setIsInput(0);
            mDataList.setIsUpdate(0);
            mDataList.setIsQuery(0);
            mDataList.setIsArchiveNo(0);
            // mDataList.setIsNoEmpty(0);
            mDataList.setIsHidden(0);
            mDataList.setCheckChongfu(0);
            mDataList.setIsExport(1);
            mDataList.setIsImport(0);
            mDataList.setIsMetadata(0);
            // mDataList.setShowType(4);
            mDataList.setZsfl("1");
            mDataList.setThWidth(StringUtils.isNotEmpty(data.getThWidth()) ? Integer.valueOf(data.getThWidth()):null);
            mDataList.setThAlign(data.getThAlign());
            mDataList.setCreatorId(user.getUserId());
            mDataList.setCreateTime(DateUtils.getNowDate());
            yqdaMdataListMapper.insertTenantMdataList(mDataList);
        }
        return 1;
    }

    /**
     * 修改元数据明细
     *
     * @param yqdaMdataList 元数据明细
     * @return 结果
     */
    @Override
    public int updateTenantMdataList(TenantMdataList yqdaMdataList, String ids)
    {
        //查询是否重复
        String [] idd = ids.split(",");
        if (yqdaMdataList.getIsHidden() != null && yqdaMdataList.getIsHidden() ==0 && yqdaMdataList.getChangefiled().equals("isHidden") ){
            List<String> strings = yqdaMdataListMapper.selectTenantMdataIsHiddenSum(yqdaMdataList.getTableName(), ids);
            if(strings.size()>50&&!strings.contains(yqdaMdataList.getFieldName())){
                throw new ServiceException("元数据明细中展示字段超过50个,请进行修改！");
            }
        }
        if(idd.length == 1){
            TenantMdataList select = new TenantMdataList();
            select.setGroupId(yqdaMdataList.getGroupId());
            select.setType(yqdaMdataList.getType());
            select.setFieldCaption(yqdaMdataList.getFieldCaption());
            List<TenantMdataList> mdataLists = yqdaMdataListMapper.selectTenantMdataListListPrecise(select);
            if(mdataLists.size() > 0 && !idd[0].equals(String.valueOf(mdataLists.get(0).getId()))){
                throw new ServiceException("元数据明细中显示名称重复！");
            }
        }

        return yqdaMdataListMapper.updateTenantMdataList(yqdaMdataList,ids);
    }

    /**
     * 批量删除元数据明细
     *
     * @param ids 需要删除的元数据明细主键
     * @return 结果
     */
    @Override
    public int deleteTenantMdataListByIds(Long[] ids)
    {
        return yqdaMdataListMapper.deleteTenantMdataListByIds(ids,new TenantMdataList().getTableName());
    }

    /**
     * 删除元数据明细信息
     *
     * @param id 元数据明细主键
     * @return 结果
     */
    @Override
    public int deleteTenantMdataListById(Long id)
    {
        return yqdaMdataListMapper.deleteTenantMdataListById(id,new TenantMdataList().getTableName());
    }

    @Override
    public List<TenantFields> getGroupDataList(TenantFields yqfields, Long groupId) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        String tableName = tenantMdataList.getTableName();
        Integer type = Integer.valueOf(yqfields.getType());
        return tenantFieldsMapper.getGroupDataList(yqfields,type,groupId,tableName);
    }

    @Override
    public String copyIsRepeat(String ids, Long groupId,Integer type) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        tenantMdataList.setGroupId(groupId);
        tenantMdataList.setType(type);
        String msg = yqdaMdataListMapper.copyIsRepeat(tenantMdataList,ids);
        return msg;
    }

    @Override
    @Transactional
    public int copyToGroup(String ids, Long groupId, Integer type) {
        List<TenantMdataList> dataLists = yqdaMdataListMapper.getDataListsByIds(ids,new TenantMdataList().getTableName());
        for(TenantMdataList data:dataLists){
            TenantMdataList mdataList = new TenantMdataList();
            mdataList.setFieldName(data.getFieldName());
            mdataList.setGroupId(groupId);
            mdataList.setType(data.getType());
            TenantMdataList num = yqdaMdataListMapper.isExist(mdataList);
            if(num != null && type == 1){
                //覆盖
                data.setId(num.getId());
                data.setGroupId(groupId);
                yqdaMdataListMapper.updateTenantMdataList(data, String.valueOf(data.getId()));
            }else if(num != null && type == 2){
                //跳过
                continue;
            }else {
                data.setId(null);
                data.setGroupId(groupId);
                yqdaMdataListMapper.insertTenantMdataList(data);
            }
        }
        return 0;
    }

    @Override
    @Transactional
    public void importHddaMDataList(List<TenantMdataList> dataLists, Long groupId, Integer type) {
        for(TenantMdataList data:dataLists){
            TenantMdataList mdataList = new TenantMdataList();
            mdataList.setFieldName(data.getFieldName());
            mdataList.setGroupId(groupId);
            mdataList.setType(data.getType());
            TenantMdataList num = yqdaMdataListMapper.isExist(mdataList);
            if(num != null && type == 1){
                //覆盖
                data.setId(num.getId());
                data.setGroupId(groupId);
                yqdaMdataListMapper.updateTenantMdataList(data, String.valueOf(data.getId()));
            }else if(num != null && type == 2){
                //跳过
                continue;
            }else {
                data.setId(null);
                data.setGroupId(groupId);
                yqdaMdataListMapper.insertTenantMdataList(data);
            }
        }
    }

    @Override
    public Map<Integer, Object> getIsExport(Long groupId, Integer type) {
        TenantMdataList select = new TenantMdataList();
        select.setType(type);
        select.setGroupId(groupId);
        select.setIsImport(1);
        List<TenantMdataList> mdataLists = yqdaMdataListMapper.selectTenantMdataListList(select);
        List<List<String>> headList = new ArrayList<>();
        Map<Integer,String []> mapList = new HashMap<>();
        for(int i = 0;i<mdataLists.size();i++){
            List<String> titile = new ArrayList<>();
            titile.add((mdataLists.get(i).getIsNoEmpty()==1?"*":"")+mdataLists.get(i).getFieldCaption());
            headList.add(titile);
            if(mdataLists.get(i).getShowType() == 5){
                List<TenantSysDictData> dictData = dictTypeService.selectDictDataByType(mdataLists.get(i).getFieldName());
                if(dictData!=null && dictData.size()>0){
                    String[] dict = new String[dictData.size()];
                    for (int j = 0;j<dictData.size();j++){
                        dict[j] = dictData.get(j).getDictLabel();
                    }
                    mapList.put(i,dict);
                }
            }
        }
        Map<Integer,Object> data = new HashMap<>();
        data.put(0,headList);
        data.put(1,mapList);
        return data;
    }

    @Override
    public List<Map<String,Object>> selectYqdaMdataListListforshy(Long groupId,Integer type,String fieldCaption,String fieldName,Long categoryId) {
        if(StringUtils.isNotEmpty(fieldName) && !"null".equals(fieldName) && fieldName.contains("_")){
            fieldName = fieldName.replace("_","\\_");
        }
        return yqdaMdataListMapper.selectYqdaMdataListListforshy(groupId,type,fieldCaption,fieldName,categoryId,new TenantMdataList().getTableName(),new TenantMdataListShy().getTableName());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addmdatatoshy(JSONArray ids, Integer type, Long categoryId,Long groupId) {
        List<TenantMdataList> dataListsByIds = yqdaMdataListMapper.getDataListsByIds(ids.toString().replace("[","").replace("]","").replace("\"",""),new TenantMdataList().getTableName());
        for (TenantMdataList mdata:dataListsByIds) {
            Long id=yqdaMdataListMapper.selectshybyid(mdata.getId(),type,groupId,categoryId,new TenantMdataListShy().getTableName());
            TenantMdataListShy yqdaMdataListShy=new TenantMdataListShy();
            yqdaMdataListShy.setMdataId(mdata.getId());
            yqdaMdataListShy.setGroupId(groupId);
            yqdaMdataListShy.setType(type);
            yqdaMdataListShy.setFieldName(mdata.getFieldName());
            yqdaMdataListShy.setCategoryId(categoryId);
            yqdaMdataListShy.setId(SnowflakeIdGenerator.generateId());
            if (null==id){
                yqdaMdataListMapper.addmdatatoshy(yqdaMdataListShy);
            }else{
                //存储项都不会改变,不更新
                //yqdaMdataListShy.setId(id);
                //yqdaMdataListMapper.updatemdatatoshy(yqdaMdataListShy);
            }
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deletemdatafromshy(JSONArray ids, Integer type, Long categoryId, Long groupId) {
        for (int i = 0; i < ids.size(); i++) {
            TenantMdataListShy yqdaMdataListShy=new TenantMdataListShy();
            yqdaMdataListShy.setMdataId(ids.getLong(i));
            yqdaMdataListShy.setType(type);
            yqdaMdataListShy.setCategoryId(categoryId);
            yqdaMdataListShy.setGroupId(groupId);
            yqdaMdataListMapper.deletemdatafromshy(yqdaMdataListShy);
        }
        return 1;
    }

    @Override
    public int batchUpdateTenantMdataList(TenantMdataList tenantMdataList, String ids) {
        //查询是否重复
        String [] idd = ids.split(",");
//        if(idd.length == 1){
//            TenantMdataList select = new TenantMdataList();
//            select.setGroupId(yqdaMdataList.getGroupId());
//            select.setType(yqdaMdataList.getType());
//            select.setFieldCaption(yqdaMdataList.getFieldCaption());
//            List<TenantMdataList> mdataLists = yqdaMdataListMapper.selectTenantMdataListListPrecise(select);
//            if(mdataLists.size() > 0 && !idd[0].equals(String.valueOf(mdataLists.get(0).getId()))){
//                throw new ServiceException("元数据明细中显示名称重复！");
//            }
//        }
//        if (tenantMdataList.getIsHidden() != null && tenantMdataList.getIsHidden() ==0){
//            List<String> strings = yqdaMdataListMapper.selectTenantMdataIsHiddenSum(tenantMdataList.getTableName(), ids);
//            if(strings.size()>50&&!strings.contains(tenantMdataList.getFieldName())){
//                throw new ServiceException("元数据明细中展示字段超过50个,请进行修改！");
//            }
//        }
        return yqdaMdataListMapper.updateTenantMdataList(tenantMdataList,ids);
    }

    @Override
    public List<TenantMdataList> selectTenantMdataListListforexport(Long groupId, Integer type, String fieldName, List ids) {
        return yqdaMdataListMapper.selectTenantMdataListListforexport(groupId,type,fieldName,ids,new TenantMdataList().getTableName());
    }
}
